// pages/news/news.js
// const webSocket = require('../../utils/webSocket.js'); 
var isFirstMsg = true
var msgQueue = []
var text = 0
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dataInfo: {},
    newsList: {},
    loading: true,
    allUserList: []
  },

  // 点击跳转到聊天界面
  clickJumpChat: function(e) {
		var num = this.data.newsList[e.currentTarget.dataset.index].hasNewMsg
		text -= num
		if (text > 0) {
			wx.setTabBarBadge({
				index: 0,
				text: String(text)
			})
		} else {
			text = 0
			wx.hideTabBarRedDot({
				index: 0
			})
		}
		this.data.newsList[e.currentTarget.dataset.index].hasNewMsg = 0
		this.setData({
			newsList: this.data.newsList
		})

		console.log(JSON.stringify(e.currentTarget.dataset))
		var msg = JSON.stringify(e.currentTarget.dataset)
		
    wx.navigateTo({
      url: '../chat/chat?msg=' + msg
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this
    wx.setNavigationBarTitle({
      title: '消息'
    })

    // 获取缓存里面的客服信息
    try {
      var value = wx.getStorageSync('islogin')
      if (value) {
        console.log(value)
        // 如果缓存里面有登录信息则发送请求
        this.setData({
          dataInfo: value
        })
      } else {
        // wx.navigateTo({
        // 	url: '../login/login'
        // })
      }
    } catch (e) {
      console.log(e)
    }

    // 获取最近的做多50个聊天列表
    wx.request({
      url: app.globalData.baseUrl + '/api/user/autopushmsg',
      method: 'GET',
      data: {
        cs_id: this.data.dataInfo.user_info.id
      },
      success: function(res) {
        console.log(res)
        if (res.data.status === 1) {
          that.sortNewsList(res.data.result)
        }
      }
    })

    // 获取所有联系人的数据
    wx.request({
      url: app.globalData.baseUrl + '/api/csuser/getalluser',
      method: 'Get',
      data: {
        butt_id: this.data.dataInfo.user_info.id
      },
      success: function(res) {
        console.log(res)
        if (res.data.status === 1) {
          that.setData({
            allUserList: res.data.msg
          })
        }
      }
    })
    this.setData({
      loading: false
    })
  },



  // 对聊天列表进行排序，最近的聊天放在最上面
  sortNewsList: function(data) {
    var that = this
    var haschatlog = []
    var nochatlog = []
    data.forEach(function(item) {
      if (item.chatlog.length !== 0) {
        haschatlog.push(item)
      } else {
        nochatlog.push(item)
      }
      item.hasNewMsg = 0
    })
    haschatlog.sort(function(a, b) {
      var value1 = a.chatlog[a.chatlog.length - 1].send_time;
      var value2 = b.chatlog[b.chatlog.length - 1].send_time;
      return value2 - value1;
    })
    console.log(haschatlog)
    var chatlog = haschatlog.concat(nochatlog)

    chatlog.forEach(function(item) {
      // item.chatlog.reverse()
      if (item.chatlog !== '') {
        item.chatlog.forEach(function(innerItem) {
          innerItem.send_time = that.timeChange(innerItem.send_time)
        })
      }
    })
    that.setData({
      newsList: chatlog
    })
  },

  // 将时间戳转换为时间
  timeChange: function(timestamp) {
    var date = new Date(timestamp * 1000) // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
    // var Y = date.getFullYear() + '-'
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
    var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
    var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
    var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
    var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
    return M + D + h + m + s
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    app.sureConnect()
    wx.onSocketOpen(function(res) {
      that.onopen(res)
    })

    wx.onSocketMessage(function(res) {
      that.onmessage(res)
    })
		
		// 将缓存里面的新消息显示到页面上
		wx.getStorage({
			key: 'newMsgList',
			success(res) {
				console.log(res.data)
				res.data.forEach(function (item) {
					that.handleMessage(item)
				})
				wx.removeStorage({
					key: 'newMsgList',
					success(res) {
						console.log(res.data)
					}
				})
			}
		})
  },

  onopen: function(res) {
    console.log(res)
  },

  onmessage: function(res) {
    var that = this
    var data = JSON.parse(res.data)
    if (data.event === 're_connect') {
      app.heartbeat()
    } else if (data.event === 'heartbeat_new') {
      app.heartbeat()
    } else if (data.event === 'sendMsg') {
      // 接受到消息后x显示列表右边的角标
      console.log(res)
      var data = JSON.parse(res.data).data
      console.log(data)
      that.handleMessage(data)
    }
  },

  // 处理接受到的消息
  handleMessage: function(data) {
		text += 1
		wx.setTabBarBadge({
			index: 0,
			text: String(text)
		})
    var that = this
    // 判断是否在最近的消息列表中
    var isLatestList = that.inArrayLatest(data, that.data.newsList)
		console.log(isLatestList)
    if (!isLatestList) {
      // 如果不在最近的消息列表里面就去联系人的列表中查openid
      // 判断是否在联系人的列表中
      // var isAllUserList = that.inArrayAll(data, that.data.allUserList)
			var isAllUserList = false
      // 
      if (!isAllUserList) {
        // 根据openid获取用户的信息
				// 如果是第一条消息
				if (isFirstMsg) {
					isFirstMsg = false
					wx.request({
						url: app.globalData.baseUrl + '/api/user/getsqluser',
						method: 'GET',
						data: {
							openid: data.openid
						},
						success: function (res) {
							console.log(res)
							var newArray = res.data.result
							newArray.hasNewMsg = 1
							newArray.chatlog = [{
								appid: data.appid,
								content: data.content,
								cs_id: data.cs_id,
								send_time: that.timeChange(data.send_time),
								openid: data.openid,
								send_type: data.send_type,
								type: data.type
							}]
							that.data.newsList.unshift(newArray)
							that.setData({
								newsList: that.data.newsList
							})
							isFirstMsg = true
							for (var i = 0; i < msgQueue.length; i++) {
								that.handleMessage(data)
							}
						}
					})
				} else {
					msgQueue.push(data)
				}
      }
    }
  },

  // 判断openid是否在最近的消息列表中
  inArrayLatest: function(data, array) {
		console.log(data)
		console.log(array)
    var that = this
    for (var i = 0; i < array.length; i++) {
      if (array[i].openid === data.openid) {
        array[i].hasNewMsg += 1
        array[i].chatlog.push({
          appid: data.appid,
          content: data.content,
          cs_id: data.cs_id,
          send_time: that.timeChange(data.send_time),
          openid: data.openid,
          send_type: data.send_type,
          type: data.type
        })
        var arrStart = array[i]
        array.splice(i, 1)
        array.unshift(arrStart)
        that.setData({
          newsList: array
        })
        return true
      }
      return false
    }
  },

  // 判断openid是否在所有的联系人列表中
  inArrayAll: function(data, array) {
    var that = this
    for (var i = 0; i < array.length; i++) {
      if (array[i].openid === data.openid) {
        var newArray = array[i]
        newArray.hasNewMsg = 1
        newArray.chatlog = [{
          appid: data.appid,
          content: data.content,
          cs_id: data.cs_id,
          send_time: that.timeChange(data.send_time),
          openid: data.openid,
          send_type: data.send_type,
          type: data.type
        }]
        console.log(that.data.newsList)
        console.log(newArray)
        that.data.newsList.unshift(newArray)
        that.setData({
          newsList: that.data.newsList
        })
        return true
      }
      return false
    }
  },



  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    // webSocket.closeSocket();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})